package com.lv.suyiyong.hfrwork.fragment

import android.Manifest
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.imageview.ShapeableImageView
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.base.BaseFragment
import com.lv.common.imp.OnPositionTListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.LogUtil
import com.lv.common.utils.PermissionXUtils
import com.lv.common.utils.PermissionXUtilsCallback
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxSpUtils
import com.lv.common.widget.imageview.CustomBlurTransformation
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.adapter.MineTabAdapter
import com.lv.service.bean.CommonTab
import com.lv.service.bean.FindCountsBean
import com.lv.service.event.MessageReadEvent
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.utils.getUserAtName
import com.lv.suyiyong.hfrwork.R
import com.lv.suyiyong.hfrwork.databinding.FragmentMineBinding
import com.tencent.imsdk.v2.V2TIMConversation
import com.tencent.imsdk.v2.V2TIMConversationListener
import com.tencent.imsdk.v2.V2TIMConversationResult
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMValueCallback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/2/10 11:24 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class MineFragment : BaseFragment(), OnClickListener {
    private var mUserInfo: UserInfo? = null

    private var mIvLogo: ShapeableImageView? = null
    private var mivBg: ImageView? = null
    private val mBeans = mutableListOf<CommonTab>()
    private var mAdapter: MineTabAdapter? = null

    private var mTvAreaName: TextView? = null
    private var mTvAreaPhone: TextView? = null
    private var mTvName: TextView? = null
    private var mTvLocation: TextView? = null

    private var mCpyid: String? = YgxSpUtils.getString(Constants.KEY_CPYID)
    private val serviceViewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.fragment_mine

    override fun bindView(view: View, savedInstanceState: Bundle?): ViewDataBinding {
        return FragmentMineBinding.bind(view).apply {
            StatusBarUtil.setHeightAndPadding(requireContext(), viewTop)
//            mIvLogo = ivLogo

            ivSetting.setOnClickListener(this@MineFragment)
            initAdapter()
        }
    }

    override fun onResume() {
        super.onResume()
//        initStatusBar(requireActivity(), true, true)
    }

    override fun initData() {
        super.initData()
        UserDbHelper.getLiveUserInfo(requireContext()).observeKt { userInfos ->
            userInfos?.let {
                mUserInfo = userInfos
                // "25"	模糊度，取值范围1~25
                // "3"	图片缩放3倍后再进行模糊，一般缩放3-5倍
//                Glide.with(requireContext()).load(userInfos.logo)
//                    .transform(BlurTransformation(10, 3)).into(mivBg!!)
                Glide.with(requireContext()).load(userInfos.image)
                    .apply(
                        RequestOptions.bitmapTransform(
                            CustomBlurTransformation(
                                requireContext(),
                                10
                            )
                        )
                    ).into(mivBg!!)

                mIvLogo?.LoadSrc(userInfos.image)
                mTvName?.text = userInfos.name
                val section = userInfos.getUserAtName().replace("_", "  ")

//                mTvLocation?.text = section + "  " + userInfos.bpro
                mTvLocation?.text = section
                val role = userInfos.role ?: ""
                mBeans.clear()
                mBeans.add(CommonTab("", "", "我的工具", 0, true))
//                if (role.contains("I")) {
                mBeans.add(CommonTab("0", "I", "品牌热卖", R.drawable.icon_dzsk, false))
//                }
//                if (role.contains("J")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0",
//                            "J",
//                            "电子回执",
//                            R.drawable.icon_home_book_tag,
//                            false
//                        )
//                    )
//                }
//                if (role.contains("K")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "K", "找货啦", R.drawable.icon_find_goods, false
//                        )
//                    )
//                }
//                if (role.contains("L")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "L", "邀请码", R.drawable.icon_code_syy, false
//                        )
//                    )
//                }
//                if (role.contains("M")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "M", "审批", R.drawable.icon_sp, false
//                        )
//                    )
//                }
//                if (role.contains("N")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "N", "商机信息", R.drawable.icon_sjxx, false
//                        )
//                    )
//                }
//                if (role.contains("O")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "O", "成员管理", R.drawable.icon_cygl, false
//                        )
//                    )
//                    mBeans.add(
//                        CommonTab(
//                            "0", "O_O", "客户迁移", R.drawable.icon_khqy, false
//                        )
//                    )
//                }
//                val userManager = mUserInfo?.isUserManagerForSaler("3") ?: false
//                if (userManager) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "ZZZ", "发行期数", R.drawable.icon_fxqs, false
//                        )
//                    )
//                }
//                if (role.contains("Y")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "Y", "手动排序", R.drawable.icon_sdpx, false
//                        )
//                    )
//                }
//                if (role.contains("a")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "a", "发券中心", R.drawable.icon_dzsk, false
//                        )
//                    )
//                }
//                if (role.contains("d")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "d", "推广返现", R.drawable.icon_tgfx, false
//                        )
//                    )
//                }
//                if (role.contains("g")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "g", "店铺充值", R.drawable.icon_recharge_mine, false
//                        )
//                    )
//                }
//                if (role.contains("g")) {
//                    mBeans.add(
//                        CommonTab(
//                            "0", "j", "亨富然", R.drawable.icon_recharge_mine, false
//                        )
//                    )
//                }

            }

        }

        // 1. 设置会话监听
        V2TIMManager.getConversationManager().addConversationListener(v2TIMConversationListener)
        // 2. 先拉取50个本地会话做 UI 展示，nextSeq 第一次拉取传0
        V2TIMManager.getConversationManager().getConversationList(
            0, 50,
            object : V2TIMValueCallback<V2TIMConversationResult?> {
                override fun onSuccess(v2TIMConversationResult: V2TIMConversationResult?) {
                    val nextSeq = v2TIMConversationResult?.nextSeq
                    LogUtils.e(
                        "imsdk",
                        "success nextSeq:" + nextSeq + ", isFinish:" + v2TIMConversationResult?.isFinished
                    )
                    val v2TIMConversationList = v2TIMConversationResult?.conversationList
                    v2TIMConversationList?.let {
                        refreshTabCount(v2TIMConversationList)
                    }

                }

                override fun onError(code: Int, desc: String) {
                    LogUtils.e("imsdk", "failure, code:$code, desc:$desc")
                }


            })

    }

    private val v2TIMConversationListener: V2TIMConversationListener =
        object : V2TIMConversationListener() {
            // 3.1 收话新增的回调
            @RequiresApi(api = Build.VERSION_CODES.N)
            override fun onNewConversation(conversationList: List<V2TIMConversation>) {
                super.onNewConversation(conversationList)
                LogUtil.e("onNewConversation", "onNewConversation")
            }

            // 3.2 收到会话更新的回调
            @RequiresApi(api = Build.VERSION_CODES.N)
            override fun onConversationChanged(conversationList: List<V2TIMConversation>) {
                if (conversationList.isEmpty()) {
                    return
                }
                refreshTabCount(conversationList)

            }
        }

    val sjMap = mutableMapOf<String, String>(
        "code" to "1",
        "opportunity" to "1",
        "approve" to "1",
        "sendOrder" to "1",
    )

    private fun refreshTabCount(conversationList: List<V2TIMConversation>) {
        val sjxx =
            conversationList.filter { item -> "c2c_${Constants.SYY_YWY_SJXX}".contains(item.conversationID) }
        val spxx =
            conversationList.filter { item -> "c2c_${Constants.SYY_YWY_SP}".contains(item.conversationID) }
        val findgoods =
            conversationList.filter { item -> "c2c_${Constants.SYY_YWY_FIND_GOODS}".contains(item.conversationID) }
        if (!sjxx.isNullOrEmpty() || !spxx.isNullOrEmpty() || !findgoods.isNullOrEmpty()) {
            findCount(sjMap)
        }


    }

    private fun findCount(paramsMap: Map<String, String>) {
        lifecycleScope.launchWhenCreated {
            this.launch {
                val result: DataResult<BaseYgxRsp> =
                    myScope.async {
                        serviceViewModel.findCount(
                            paramsMap
                        )
                    }.await()
                parseResult(result)
            }
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<FindCountsBean> { code, data, message, result ->
                data?.let {

                    refreshTab("M", data.approve)
                    refreshTab("N", data.opportunity)
                    refreshTab("K", data.sendOrder)

                }

            }
            onBizError<Any> { code, message, data ->
            }
        }
    }


    private fun refreshTab(tag: String, unreadCount: Int) {
        for (i in 0 until mBeans.size) {
            val commonTab = mBeans[i]
            if (commonTab.image == tag) {
                var mCount = "$unreadCount"
                if (unreadCount > 99) {
                    mCount = "99+"
                }
                mBeans[i].id = mCount
                mAdapter?.notifyDataSetChanged()
                break
            }
        }
    }

    private fun FragmentMineBinding.initAdapter() {
        val gridLayoutManager = GridLayoutManager(requireContext(), 4)
        mAdapter = MineTabAdapter(mBeans)
        adapter = mAdapter
        rvContent.layoutManager = gridLayoutManager
        rvContent.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(19.0f),
                SizeUtils.dp2px(0f),
                true
            )
        )
        val topHeader = View.inflate(context, R.layout.fragment_mine_header, null)
        mivBg = topHeader.findViewById<ImageView>(R.id.iv_bg)
        mIvLogo = topHeader.findViewById<ShapeableImageView>(R.id.iv_head)
        mTvAreaName = topHeader.findViewById<TextView>(R.id.tv_area_name)
        mTvAreaPhone = topHeader.findViewById<TextView>(R.id.tv_area_phone)
        mTvName = topHeader.findViewById<TextView>(R.id.tv_name)
        mTvLocation = topHeader.findViewById<TextView>(R.id.tv_location)
        mAdapter?.addHeaderView(topHeader)
        topHeader.findViewById<RelativeLayout>(R.id.rl_head).setOnClickListener {
            ARouter.getInstance().build(ARoutUtils.UserInfoActivity)
                .withParcelable("userinfo", mUserInfo).navigation()

        }
    }

    private fun checkPermissionLoction(type: String) {
        val permissions = mutableListOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_BACKGROUND_LOCATION,
        )
        var hint = ""
        when (type) {
            "d" -> hint = "推广返现需要授予位置权限"////推广返现-推广信息上传
        }
        // 用于在您浏览、搜索或参与特定活动时，向您展示当前城市服务信息，以提升体验。不申请该权限不影响APP的正常使用。是否同意去申请该权限？
        PermissionXUtils.checkPermissBefore(
            this, permissions, hint,
            object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>,
                ) {
                    if (allGranted) {
//                        locationUtil.initLocationManager()
//                        LocationUtils.getInstance().getLocations(requireContext())
                        when (type) {
                            "d" -> {//推广返现-推广信息上传
//                                ARouter.getInstance().build(ARoutUtils.PushInfoSelectedActivity)
//                                    .navigation()
                            }
                        }

                    }
                }


            },
        )
    }

    override fun initEvents() {
        super.initEvents()
        mAdapter?.onViewItemClickListener = OnPositionTListener { position, data ->
            if (!data.isNullOrEmpty()) {
                when (data) {
//                    "I" -> {//电子书刊
//                        ARouter.getInstance().build(ARoutUtils.BookActivity)
//                            .navigation()
//                    }
//                    "J" -> {//电子回执
//                        ARouter.getInstance().build(ARoutUtils.BookHZActivity)
//                            .navigation()
//
//                    }
//                    "K" -> {//我要找货
//                        ARouter.getInstance().build(ARoutUtils.MessageFindGoodsActivity)
//                            .navigation()
//                    }
//
//                    "L" -> {//邀请码
//                        ARouter.getInstance().build(ARoutUtils.InviteActivity)
//                            .navigation()
//
//                    }
//
//                    "M" -> {//审批
//                        ARouter.getInstance().build(ARoutUtils.MessageApproveActivity)
//                            .withInt("type", 1)
//                            .navigation()
//
//                    }
//
//                    "N" -> {//商机信息
//                        ARouter.getInstance().build(ARoutUtils.MessageOpportunityActivity)
//                            .withInt("type", 1)
//                            .navigation()
//
//                    }
//
//                    "O" -> {//成员管理
////                        ARouter.getInstance().build(ARoutUtils.ManagerWorkerActivity)
////                            .withParcelable("userinfo", mUserInfo)
////                            .navigation()
//                        ARouter.getInstance().build(ARoutUtils.TeamManagerActivity)
//                            .withString("salerid", mUserInfo?.id)
//                            .navigation()
//
//                    }
//
//                    "O_O" -> {//客户迁移
//                        ARouter.getInstance().build(ARoutUtils.ClientMoveActivity)
//                            .withParcelable("userinfo", mUserInfo)
//                            .navigation()
//                    }
//
//                    "ZZZ" -> {//发行期数
//                        ARouter.getInstance().build(ARoutUtils.ReceiptPeriodsActivity).navigation()
//                    }
//
//                    "I" -> {//进销存
//                        showToast(data)
//
//                    }
//
//                    "Y" -> {//手动排序
//                        ARouter.getInstance().build(ARoutUtils.SortCompanyActivity).navigation()
//                    }
//
//                    "a" -> {//发券中心
//                        ARouter.getInstance().build(ARoutUtils.CouponCenterRedActivity).navigation()
//                    }
//
//                    "d" -> {//推广返现-推广信息上传
//                        checkPermissionLoction("d")
//
//                    }
//
//                    "g" -> {//店铺充值
//                        ARouter.getInstance()
//                            .build(ARoutUtils.CompanyRechargeActivity).navigation()
//                    }
//
//                    "j" -> {//亨富然
//                        ARouter.getInstance()
//                            .build(ARoutUtils.ClientsHFRActivity).navigation()
//                    }
                }
            }

        }
        rigestEventBus()
    }

    private fun rigestEventBus() {
        LiveEventBus.get(MessageReadEvent::class.java).observe(
            this
        ) { s ->
            if (s != null) {
                if (s.location == 0) {//刷新商机消息
                    findCount(sjMap)
                }
            }
        }
    }


    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
//        if (!hidden) {
//            initStatusBar(requireActivity(), true, true)
//        }
    }

    companion object {
        @JvmStatic
        fun newInstance() = MineFragment()
    }

    override fun onClick(v: View?) {
        when (v?.id) {

            R.id.iv_setting -> {
                ARouter.getInstance().build(ARoutUtils.SettingActivity)
                    .withParcelable("userinfo", mUserInfo).navigation()
            }


        }

    }


}